// 1.导入koa-router
var Router = require("koa-router");
var fs = require("fs");
const Mock = require("mockjs");

// 2.创建一个router对象
var router = new Router();

// 3.查找全部数据
router.all("/getList", function (ctx) {
  var list = require("./users.json");
  ctx.body = list;
});
router.all("/add", function (ctx) { 
  var list = require("./users.json");
  var obj = ctx.request.body;
  obj.userId = Mock.mock(/[a-z]{5}\d{5}/);
  list.push(obj);
  ctx.body = obj;
  // fs.writeFileSync('users.json',JSON.stringify(list));
});
router.all("/madeData", function (ctx) {
  ctx.body = "add";
});

// 获取详情接口
router.all("/detail", function (ctx) {
  var list = require("./users.json");
  var userId = ctx.query.userId;
  var user = list.find((item) => item.userId === userId);
  ctx.body = user;
});
router.all("/update", function (ctx) {
  ctx.body = "update";
});

// 删除接口
router.all("/del", function (ctx) {
  // ctx.body= 2222;
  var userId = ctx.query.userId;
  var list = require("./users.json");
  var index = list.findIndex(function (item) {
    return item.userId === userId;
  }); 
  if (index > -1) {
    var user = list.splice(index, 1); 
    ctx.body = {
      msg: '删除成功',
      user: user
    };
    fs.writeFileSync("./users.json", JSON.stringify(list));
  } else {
    throw Error('删除失败');
  }
});

// 导出路由对象
module.exports = router;
